package com.example.time.encoder;

import com.example.time.pojo.UnixTime;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * @author linfeng
 * @date 2022/1/17 16:54
 */
public class TimeEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        UnixTime unixTime = (UnixTime) msg;
        ByteBuf encoded = ctx.alloc().buffer(8);
        encoded.writeLong(unixTime.getTimestamp());

        // 将promise传递给write方法以便获知数据是否写入成功
        ctx.write(encoded, promise);
    }
}
